package com.yunyi.integration.utils;


import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;

/**
 * 校验POJO注解类
 *
 * @author Yunyi
 * @date 2018/10/12.
 */
public class ValidationUtil {
    /**
     * 私有化构造
     */
    private ValidationUtil() {
    }

    /**
     * Validator工厂对象
     */
    private static final ValidatorFactory VALIDATOR_FACTORY = Validation.buildDefaultValidatorFactory();
    /**
     * 预置Validator对象
     */
    private static Validator validator = VALIDATOR_FACTORY.getValidator();

    public static Validator build() {
        return VALIDATOR_FACTORY.getValidator();
    }

    /**
     * 校验JavaBean-默认并非全部检查
     *
     * @param obj 待校验的JavaBean
     * @return 校验返回字符串，如果为空则校验通过，否则返还失败信息
     */
    public static String validate(Object obj) {
        final boolean isValidateAll = false;
        return validate(obj, isValidateAll);
    }

    /**
     * 校验JavaBean
     *
     * @param obj           待校验的JavaBean
     * @param isValidateAll 是否进行完整的JavaBean校验，如果为true则返回全部属性以及方法校验结果，否则校验未通过则返回
     * @return 校验返回字符串，如果为空则校验通过，否则返还失败信息
     */
    public static String validate(Object obj, boolean isValidateAll) {
        StringBuilder builder = new StringBuilder();
        for (ConstraintViolation<Object> constraintViolation : validator.validate(obj)) {
            builder.append(constraintViolation.getMessage());
            if (isValidateAll) {
                builder.append(",");
            } else {
                if (builder.length() > 0) {
                    return builder.toString();
                }
            }
        }
        return builder.toString();
    }

    public static ValidatorFactory getValidatorFactory() {
        return VALIDATOR_FACTORY;
    }


}
